package com.rightsidetech.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.commom.base.PageRequest;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.enums.SystemParamsEnum;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.system.dtos.request.SystemParamReq;
import com.rightsidetech.system.dtos.response.SystemParamResp;
import com.rightsidetech.system.entity.SysSystemParam;
import com.rightsidetech.system.mapper.SysSystemParamMapper;
import com.rightsidetech.system.service.SystemParamService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.util.Date;
import java.util.List;

/**
 * @Author: yhr
 * @Date: 2021-11-10 10:50
 */
@Service("systemParamServiceImpl")
public class SystemParamServiceImpl implements SystemParamService {
    @Resource
    private SysSystemParamMapper sysSystemParamMapper;
    @Override
    public ResponseData<PageInfo<SystemParamResp>> paramPage(PageRequest page) {
        PageHelper.startPage(page.getPageNo(), page.getPageSize());
        List<SystemParamResp> list = sysSystemParamMapper.page(page);
        return ResponseData.success(new PageInfo<>(list));
    }

    @Override
    public ResponseData updateData(SystemParamReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        int i = sysSystemParamMapper.selectById(req.getId());
        if (i < 1){
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }
        SysSystemParam systemParam = new SysSystemParam();
        systemParam.setId(req.getId());
        systemParam.setParamValue(req.getParamValue());
        systemParam.setParamDetails(req.getParamDetails());
        systemParam.setParamDescribe(req.getParamDescribe());
        systemParam.setUpdatedAt(new Date());
        sysSystemParamMapper.updateByPrimaryKeySelective(systemParam);
        return ResponseData.success();
    }

    @Override
    public ResponseData<String> getWorkTime() {
        SysSystemParam param =  sysSystemParamMapper.selectValueByKey(SystemParamsEnum.WORK_TIME.getValue());
        return ResponseData.success(param.getParamValue());
    }

    @Override
    public SysSystemParam findByParamKey(String paramKey) {
        SysSystemParam param =  sysSystemParamMapper.selectValueByKey(paramKey);
        return param;
    }

    @Override
    public SysSystemParam selectById(Long id) {
        return sysSystemParamMapper.selectByPrimaryKey(id);
    }
}
